package xin.smartlink.webview.location.demo;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    private WebView mWebView;
    private LocationWebChromeClient mLocationWebChromeClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        mWebView = findViewById(R.id.webView);
        mLocationWebChromeClient = new LocationWebChromeClient(this);
        mWebView.setWebChromeClient(mLocationWebChromeClient);
        setupWebViewEnvirment();
        mWebView.loadUrl("https://smartlink.xin/h5test/#/");
    }

    private void setupWebViewEnvirment() {
        WebSettings mWebSettings = mWebView.getSettings();
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setAllowContentAccess(true);
        mWebSettings.setSupportMultipleWindows(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        mWebView.loadUrl("https://msdev.czb365.com/?platformType=92631345&platformCode=18610899775");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mLocationWebChromeClient != null && mLocationWebChromeClient.getLocationWebChromeClientListener() != null) {
            mLocationWebChromeClient.getLocationWebChromeClientListener().onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mLocationWebChromeClient != null && mLocationWebChromeClient.getLocationWebChromeClientListener() != null) {
            if (mLocationWebChromeClient.getLocationWebChromeClientListener().onReturnFromLocationSetting(requestCode)) {
                return;
            }
        }
    }

    //返回键监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //返回上一级
    public void goBack() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }
}
